In this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with 'Implementation' in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with 'Optional' in the header.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
checkpoint1_var = {}
checkpoint1_file = 'data/checkpoint1'
checkpoint1_force = False
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = 'traffic-signs-data/train.p'
testing_file = 'traffic-signs-data/test.p'
with open(training_file, mode='rb') as f:
train_provided = pickle.load(f)
with open(testing_file, mode='rb') as f:
test_provided = pickle.load(f)
X_train_provided, y_train_provided = train_provided['features'], train_provided['labels']
X_test_provided, y_test_provided = test_provided['features'], test_provided['labels']
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 2D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below.
### Replace each question mark with the appropriate value.
import pickle
# TODO: Number of training examples
n_train_provided = len(X_train_provided)
# TODO: Number of testing examples.
n_test_provided = len(X_test_provided)
# TODO: What's the shape of an traffic sign image?
image_shape = X_train_provided.shape[1:]
# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(set(y_train_provided))
print("Number of training examples =", n_train_provided)
print("Number of testing examples =", n_test_provided)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
# Storing variables for checkpoint
checkpoint1_var['n_classes'] = n_classes
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.
### Creating Label Dictionary
import csv
label_dict = None
with open('signnames.csv', mode='r') as infile:
reader = csv.reader(infile)
next(reader, None)
label_dict = {int(rows[0]):rows[1] for rows in reader}
# Storing for checkpoint1
checkpoint1_var['label_dict'] = label_dict
### Data exploration visualization goes here
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
### Visualizing Data for Each Label
fig = plt.figure(figsize=(32,32), tight_layout={'h_pad':4})
for i in range(n_classes):
k = np.where(y_train_provided==i)
img = X_train_provided[k[0][0]]
ax = fig.add_subplot(int(n_classes/4)+1,4,i+1)
ax.imshow(img, interpolation='none')
ax.set_title(label_dict[y_train_provided[k[0][0]]])
plt.show()
### Label Distribution in Training Data
import pandas as pd
y_train_df = pd.DataFrame()
y_train_df['label'] = y_train_provided
ax = y_train_df['label'].value_counts().plot(kind='barh', figsize = (10,10), title='Samples per Class')
ax.set_yticklabels(list(map(lambda x: label_dict[x], y_train_df['label'].value_counts().index.tolist())))
for i, v in enumerate(y_train_df['label'].value_counts()):
ax.text(v + 10, i - 0.25, str(v), color='blue')
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
### Preprocess the data here.
import os
import warnings
from tqdm import tqdm
from skimage import exposure
### Histogram Equilization
def normalized_image(image_data):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return np.array([exposure.equalize_adapthist(image, clip_limit=0.03) for image in tqdm(image_data)])
if not os.path.isfile(checkpoint1_file) or checkpoint1_force:
print('Normalizing Training Images...')
X_train_provided_normalized = normalized_image(X_train_provided)
print('\nNormalizing Test Images...')
X_test_provided_normalized = normalized_image(X_test_provided)
checkpoint1_var['X_train_provided_normalized'] = X_train_provided_normalized
checkpoint1_var['y_train_provided'] = y_train_provided
checkpoint1_var['X_test_provided_normalized'] = X_test_provided_normalized
checkpoint1_var['y_test_provided'] = y_test_provided
else:
print('Checkpoint Already Exists. Data would be loaded from checkpoint. Set checkpoint1_force to force new file.')
### Storing Varibales for Checkpoint1
import pickle
if not os.path.isfile(checkpoint1_file) or checkpoint1_force:
print('Caching variables in pickle file...')
try:
with open(checkpoint1_file, 'wb') as pfile:
pickle.dump(checkpoint1_var, pfile, pickle.HIGHEST_PROTOCOL)
except Exception as e:
print('Unable to save data to', checkpoint1_file, ':', e)
raise
print('Data cached in pickle file.')
else:
print('Pickle file already created. Set checkpoint1_force to force new file.')
Describe how you preprocessed the data. Why did you choose that technique?
Answer:
Normalized image using adaptive histogram equalization for the following reasons:
import pickle
checkpoint1_file = 'data/checkpoint1'
with open(checkpoint1_file, 'rb') as pfile:
pickle_data = pickle.load(pfile)
for key in pickle_data:
exec(key + "= pickle_data['" + str(key) + "']")
del pickle_data
checkpoint2_var = {}
checkpoint2_file = 'data/checkpoint2'
checkpoint2_force = False
### Generate data additional data (OPTIONAL!)
### and split the data into training/validation/testing sets here.
### Feel free to use as many code cells as needed.
from sklearn.model_selection import train_test_split
## Splitiing Training Data in Training, Validation, Test
X_train, X_val_test, y_train, y_val_test = train_test_split(
X_train_provided_normalized,
y_train_provided,
test_size=0.30,
random_state=9345,
stratify=y_train_provided
)
X_val, X_test, y_val, y_test = train_test_split(
X_val_test,
y_val_test,
test_size=0.30,
random_state=9345,
stratify=y_val_test
)
del X_val_test
del y_val_test
checkpoint2_var['X_train'] = X_train.astype('float32')
checkpoint2_var['y_train'] = y_train
checkpoint2_var['X_val'] = X_val.astype('float32')
checkpoint2_var['y_val'] = y_val
checkpoint2_var['X_test'] = X_test.astype('float32')
checkpoint2_var['y_test'] = y_test
import keras
from keras.preprocessing.image import ImageDataGenerator
datagen = keras.preprocessing.image.ImageDataGenerator(
rotation_range=8,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=0.1,
zoom_range=0.1,
fill_mode='nearest',
horizontal_flip=False,
vertical_flip=False
)
import os
import numpy as np
from tqdm import tqdm
from sklearn.utils import shuffle
total_image_per_class = 5000
X_train_augmented = np.empty((0,32,32,3))
y_train_augmented = np.empty(0,dtype='uint8')
if not os.path.isfile(checkpoint2_file) or checkpoint2_force:
print('Augmenting Image Data...')
for i in tqdm(range(n_classes)):
index = [y_train==i]
images_for_i_class = X_train[y_train==i]
y_i_class = y_train[y_train==i]
X_train_augmented_i = np.copy(images_for_i_class)
y_train_augmented_i = np.copy(y_i_class)
for X,y in datagen.flow(images_for_i_class, y_i_class, batch_size=len(y_i_class), seed=9345+i*37):
X_train_augmented_i = np.append(X_train_augmented_i, X, axis=0)
y_train_augmented_i = np.append(y_train_augmented_i, y, axis=0)
if len(X_train_augmented_i) >= total_image_per_class:
break
X_train_augmented = np.append(X_train_augmented, X_train_augmented_i[:5000], axis=0)
y_train_augmented = np.append(y_train_augmented, y_train_augmented_i[:5000], axis=0)
else:
print('Pickle file already created. Set checkpoint2_force to force new file.')
X_train_augmented, y_train_augmented = shuffle(X_train_augmented, y_train_augmented, random_state=9345)
# Storing for checkpoint2
X_train_augmented = X_train_augmented.astype('float32')
checkpoint2_var['X_train_augmented'] = X_train_augmented
checkpoint2_var['y_train_augmented'] = y_train_augmented
checkpoint2_var.keys()
### Storing Varibales for Checkpoint2
import joblib
joblib.dump(checkpoint2_var, checkpoint2_file)
Describe how you set up the training, validation and testing data for your model. Optional: If you generated additional data, how did you generate the data? Why did you generate the data? What are the differences in the new dataset (with generated data) from the original dataset?
Answer:
The provided testing data is kept untouched, and the final model related matrix would be reported using this unseen data.
The provided training data had been divided as follow:
import pickle
## Checkpoint1 Variables
checkpoint1_file = 'data/checkpoint1'
with open(checkpoint1_file, 'rb') as pfile:
pickle_data = pickle.load(pfile)
for key in pickle_data:
exec(key + "= pickle_data['" + str(key) + "']")
del pickle_data
## Checkpoint2 Variables
import joblib
checkpoint2_file = 'data/checkpoint2'
pickle_data = joblib.load(checkpoint2_file)
for key in pickle_data:
exec(key + "= pickle_data['" + str(key) + "']")
del pickle_data
### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from tensorflow.contrib.layers import flatten
def conv2d(x, W, b, strides, padding):
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding=padding)
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k, padding):
return tf.nn.max_pool(
x,
ksize=[1, k, k, 1],
strides=[1, k, k, 1],
padding=padding)
def LeNet(x):
# Input = 32x32x3
# Hyperparameters
mu = 0
sigma = 0.1
#x_gray = tf.image.rgb_to_grayscale(x)
### Layer 1:
# Convolutional. Output = 28x28x6
# Pooling. Output = 14x14x6
W1 = tf.Variable(tf.truncated_normal([5, 5, 3, 6], mean = mu, stddev = sigma), name='W1')
b1 = tf.Variable(tf.zeros(6), name='b1')
layer1 = conv2d(x, W1, b1, 1, 'VALID')
pool1 = tf.nn.dropout(maxpool2d(layer1, 2, 'VALID'), keep_prob_conv)
### Layer 2:
# Convolutional: Output = 10x10x16
# Pooling. Output = 5x5x16
W2 = tf.Variable(tf.truncated_normal([5, 5, 6, 16], mean = mu, stddev = sigma), name='W2')
b2 = tf.Variable(tf.zeros(16), name='b2')
layer2 = conv2d(pool1, W2, b2, 1, 'VALID')
pool2 = tf.nn.dropout(maxpool2d(layer2, 2, 'VALID'), keep_prob_conv)
### Layer 3:
# Fully Connected. Output = 120
fc = flatten(pool2)
W_fc1 = tf.Variable(tf.truncated_normal([400, 120], mean = mu, stddev = sigma), name='W_fc1')
b_fc1 = tf.Variable(tf.zeros(120), name='b_fc1')
fc1 = tf.nn.relu(tf.add(tf.matmul(fc, W_fc1), b_fc1))
fc1_drop = tf.nn.dropout(fc1, keep_prob)
### Layer 4
# Fully Connected. Output = 84
W_fc2 = tf.Variable(tf.truncated_normal([120, 84], mean = mu, stddev = sigma), name='W_fc2')
b_fc2 = tf.Variable(tf.zeros(84), name='b_fc2')
fc2 = tf.nn.relu(tf.add(tf.matmul(fc1_drop, W_fc2), b_fc2))
fc2_drop = tf.nn.dropout(fc2, keep_prob)
### Layer 5
# Fully Connected. Output = n_classes
W_fc3 = tf.Variable(tf.truncated_normal([84, 43], mean = mu, stddev = sigma), name='W_fc3')
b_fc3 = tf.Variable(tf.zeros(43), name='b_fc3')
logits = tf.add(tf.matmul(fc2_drop, W_fc3), b_fc3)
return logits
x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
keep_prob_conv = tf.placeholder(tf.float32)
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, 43)
rate = 0.001
BATCH_SIZE = 128
EPOCHS = 30
logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:1, keep_prob_conv:1})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
### Train your model here.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle
from tqdm import tqdm
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
#loader = tf.train.import_meta_graph('lenet_gray.meta')
#loader.restore(sess, tf.train.latest_checkpoint('./'))
num_examples = len(X_train_augmented)
print("Training...")
print()
for i in range(EPOCHS):
print("EPOCH " + str(i+1))
X_train, y_train = shuffle(X_train_augmented, y_train_augmented)
for offset in tqdm(range(0, num_examples, BATCH_SIZE)):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:1, keep_prob_conv:1})
#break
training_accuracy = evaluate(X_train_augmented, y_train_augmented)
validation_accuracy = evaluate(X_val, y_val)
print("Training Accuracy = {:.3f}".format(training_accuracy))
print("Validation Accuracy = {:.3f}".format(validation_accuracy))
print()
#break
import os
try:
saver
except NameError:
saver = tf.train.Saver()
save_path='model1/model'
if not os.path.isabs(save_path):
save_path = os.path.abspath(os.path.join(os.getcwd(), save_path))
saver.save(sess, save_path)
print("Model saved")
test_accuracy = evaluate(X_test, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy))
What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.) For reference on how to build a deep neural network using TensorFlow, see Deep Neural Network in TensorFlow from the classroom.
Answer:
Modified LeNet Architecture
Input (32x32x3) -> Convolutional 5x5x6 -> ReLu -> MaxPool (stride of 2) -> Convolutional 5x5x16 -> ReLu -> MaxPool (stride of 2) -> Flatten (400) -> Fully Connected (120 units) -> Fully Connected (84 units) -> Fully Connected (43 units, output)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
loader = tf.train.import_meta_graph('model1/model.meta')
loader.restore(sess, tf.train.latest_checkpoint('./model1/'))
test_accuracy = evaluate(X_test_provided_normalized, y_test_provided)
print("Test Accuracy = {:.3f}".format(test_accuracy))
How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)
Answer:
What approach did you take in coming up with a solution to this problem? It may have been a process of trial and error, in which case, outline the steps you took to get to the final solution and why you chose those steps. Perhaps your solution involved an already well known implementation or architecture. In this case, discuss why you think this is suitable for the current problem.
Answer:
Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
import os
fig = plt.figure(figsize=(32,32), tight_layout={'h_pad':4})
i = 0
for file in os.listdir('data'):
if '.jpg' in file:
ax = fig.add_subplot(4,4,i+1)
img = mpimg.imread('data/' + file)
ax.imshow(img)
i+=1
plt.show()
Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It could be helpful to plot the images in the notebook.
Answer:
The images were taken from this PDF. As the images are of Germany Traffic Sign itself, it should not be difficult for model to predict.
### Run the predictions here.
### Feel free to use as many code cells as needed.
import os, sys
import numpy as np
from PIL import Image
import warnings
from skimage import exposure
### Histogram Equilization
def normalized_image(image_data):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return np.array([exposure.equalize_adapthist(image, clip_limit=0.03) for image in image_data])
size = 32, 32
logit = None
with tf.Session() as sess:
loader = tf.train.import_meta_graph('model1/model.meta')
loader.restore(sess, tf.train.latest_checkpoint('model1/'))
sess = tf.get_default_session()
fig = plt.figure(figsize=(32,32))
i = 0
for file in os.listdir('data'):
if '.jpg' in file:
im = Image.open('data/' + file)
im.thumbnail(size, Image.ANTIALIAS)
im_normalized = normalized_image(np.array([np.array(im)]))
logit = sess.run(tf.argmax(logits, 1), feed_dict={x:im_normalized, keep_prob:1.0, keep_prob_conv:1})
ax = fig.add_subplot(4,2,i+1)
img = mpimg.imread('data/' + file)
ax.imshow(img)
ax.set_title(label_dict[logit[0]])
i+=1
plt.show()
Is your model able to perform equally well on captured pictures when compared to testing on the dataset? The simplest way to do this check the accuracy of the predictions. For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate.
NOTE: You could check the accuracy manually by using signnames.csv (same directory). This file has a mapping from the class id (0-42) to the corresponding sign name. So, you could take the class id the model outputs, lookup the name in signnames.csv and see if it matches the sign from the image.
Answer:
The model is able to predict correctly on newly provided images with accuracy of 100%.
### Visualize the softmax probabilities here.
### Feel free to use as many code cells as needed.
import itertools
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
y_pred = None
with tf.Session() as sess:
loader = tf.train.import_meta_graph('model1/model.meta')
loader.restore(sess, tf.train.latest_checkpoint('model1/'))
sess = tf.get_default_session()
y_pred = sess.run(tf.argmax(logits, 1), feed_dict={x:X_test_provided_normalized, keep_prob:1.0, keep_prob_conv:1})
## Finding classes which where wrongly predicted
classes = [i for i in range(n_classes)]
plt.figure(figsize=(9,9))
plot_confusion_matrix(confusion_matrix(y_test_provided, y_pred), classes, normalize=False)
From confusion matrix it can be seen that class 11 has been wrongly predicted as class 30 in many cases.
label_dict[11]
label_dict[30]
class_11 = np.where(y_test_provided==11)
y_class_11_pred = y_pred[class_11]
X_class_11_samples = X_test_provided_normalized[class_11]
class_11_predicted_as_class_30 = np.where(y_class_11_pred==30)
X_class_11_samples_predicted_as_class_30 = X_class_11_samples[class_11_predicted_as_class_30]
## Finding top-5 classes for incorrect predictions
y_top_5 = None
with tf.Session() as sess:
loader = tf.train.import_meta_graph('model1/model.meta')
loader.restore(sess, tf.train.latest_checkpoint('model1/'))
sess = tf.get_default_session()
for X_incorrect in X_class_11_samples_predicted_as_class_30:
y_top_5 = sess.run(tf.nn.top_k(logits, k=3), feed_dict={x:[X_incorrect], keep_prob:1.0, keep_prob_conv:1})
print(y_top_5.indices)
The top 3 prediction contains class 11 in all the cases.
X_test_incorrect_pred = X_test_provided_normalized[y_pred != y_test_provided]
y_true_incorrect_pred = y_test_provided[y_pred != y_test_provided]
in_top_3 = None
in_top_5 = None
with tf.Session() as sess:
loader = tf.train.import_meta_graph('model1/model.meta')
loader.restore(sess, tf.train.latest_checkpoint('model1/'))
sess = tf.get_default_session()
in_top_3 = sess.run(tf.nn.in_top_k(logits, y_true_incorrect_pred, 3), feed_dict={x:X_test_incorrect_pred, keep_prob:1.0, keep_prob_conv:1})
in_top_5 = sess.run(tf.nn.in_top_k(logits, y_true_incorrect_pred, 5), feed_dict={x:X_test_incorrect_pred, keep_prob:1.0, keep_prob_conv:1})
## Total Incorrect Count
len(X_test_incorrect_pred)
## Incorrect Prediction but correctly predicted in Top 3
len(in_top_3[in_top_3==True])
## Incorrect Prediction but correctly predicted in Top 5
len(in_top_5[in_top_5==True])
with tf.Session() as sess:
loader = tf.train.import_meta_graph('model1/model.meta')
loader.restore(sess, tf.train.latest_checkpoint('model1/'))
sess = tf.get_default_session()
in_top_3 = sess.run(tf.nn.in_top_k(logits, y_test_provided, 3), feed_dict={x:X_test_provided_normalized, keep_prob:1.0, keep_prob_conv:1})
in_top_5 = sess.run(tf.nn.in_top_k(logits, y_test_provided, 5), feed_dict={x:X_test_provided_normalized, keep_prob:1.0, keep_prob_conv:1})
100.0 * len(in_top_3[in_top_3==True])/len(y_test_provided)
100.0 * len(in_top_5[in_top_5==True])/len(y_test_provided)
Use the model's softmax probabilities to visualize the certainty of its predictions, tf.nn.top_k could prove helpful here. Which predictions is the model certain of? Uncertain? If the model was incorrect in its initial prediction, does the correct prediction appear in the top k? (k should be 5 at most)
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
for i in range(n_classes):
cm = confusion_matrix(y_test_provided, y_pred)
cm_t = np.transpose(cm)
total_true_count = np.sum(y_test_provided==i)
total_true_pred = cm[i][i]
precision = total_true_pred / np.sum(cm_t[i].ravel())
cm[i][i] = 0
maximum_misclassified_as = np.argmax(cm[i])
percentage_classification_max_confusion = cm[i][maximum_misclassified_as] / total_true_count * 100
print("Class %s:" % label_dict[i])
print(" Accuracy = {:.2f}%".format(total_true_pred/total_true_count*100))
print(" Precision = {:.2f}%".format(precision*100))
if (cm[i][maximum_misclassified_as] != 0):
print(" Maximum Misclassified as: %s" % label_dict[maximum_misclassified_as])
print(" Misclassification Percentage for above class: {:.2f}%".format(percentage_classification_max_confusion))
print()
Answer:
The model has top-5 accuracy of 99.46%, and top-3 accuracy of 98.78%. Also, the model has accuracy and precision greater than 90% for most of the classes. The confusion matrix for the model is drawn below.
The model misclassifies class like:
classes = [i for i in range(n_classes)]
plt.figure(figsize=(9,9))
plot_confusion_matrix(confusion_matrix(y_test_provided, y_pred), classes, normalize=False)
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.